package com.example.april.controller;

import com.example.april.pojo.Customer;
import com.example.april.service.CustomerService;
import com.example.april.pojo.User;
import com.example.april.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class LoginController {

    @Autowired
    CustomerService customerService;

    @Autowired
    UserService userService;

    @GetMapping("/")
    public String root(HttpServletRequest request,Model model) {
        String id = (String)request.getSession().getAttribute("id");
        if (id == null) {
            return "login";
        }
        return "redirect:/index";
    }

    @PostMapping("/login")
    public String login(User user, HttpServletRequest request) {
        User u = userService.find(user);
        if (u != null && u.getPassword() != null && u.getPassword().equals(user.getPassword())) {
            request.getSession().setAttribute("id", u.getId());
            request.getSession().setAttribute("name", u.getName());
            return "redirect:index";
        }
        return "login";
    }

    @GetMapping("/index")
    public String index(Model model, HttpServletRequest request) {
        List<Customer> customers = customerService.findAll();
        model.addAttribute("customers", customers);
        model.addAttribute("id", request.getSession().getAttribute("id"));
        model.addAttribute("name", request.getSession().getAttribute("name"));
        return "index";
    }


    @GetMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute("id");
        request.getSession().removeAttribute("name");
        return "redirect:login";
    }

}
